import { reqGetcate, reqGetgoods } from "../../http/api"


// 数据
const initState = {
    // 1.1左边列表初始值
    arr: [],
    n: 0,
    goodsList: []
}


//action types
const types = {
    // 1.2修改type
    LIST_CHANGE_ARR: "LIST_CHANGE_ARR",
    CATE_CHANGE_N: "CATE_CHANGE_N",
    CATE_CHANGE_GOODSLIST: "CATE_CHANGE_GOODSLIST",
}


// actions creater
export const actions = {
    // 1.4修改action
    changeArr: arr => ({ type: types.LIST_CHANGE_ARR, arr }),
    // 1.6逻辑 请数据
    reqGetgoodsAction: () => (dispatch, getState) => {
        reqGetcate().then(res => {
            if (res.data.code === 200) {
                dispatch(actions.changeArr(res.data.list))
            }
        })
    },
    //   2.4
    changeN: n =>({type:types.CATE_CHANGE_N,n}),

    // 3.4
    reqgetGoodsList:goodsList=>({type:types.CATE_CHANGE_GOODSLIST,goodsList}),
    reqGoodsList:(id,index)=>{
        return (dispatch,getState)=>{
            dispatch(actions.changeN(index))
            reqGetgoods({fid:id}).then(res=>{
                if(res.data.code === 200){
                    dispatch(actions.reqgetGoodsList(res.data.list))
                }
            })
        }
    }

}


// reducer
export const cateReducer = (state = initState, action) => {
    switch (action.type) {
        // 1.3前往actions的修改逻辑
        case types.LIST_CHANGE_ARR:
            return {
                ...state,
                arr: action.arr
            }
        case types.CATE_CHANGE_N:
            return {
                ...state,
                n: action.n
            }
        case types.CATE_CHANGE_GOODSLIST:
            return {
                ...state,
                goodsList:action.goodsList
            }
        default:
            return state
    }
}

// 导出数据 一堆函数
// 1.5导出
export const getArr = state => state.cate.arr
export const getN = state => state.cate.n
export const getGoodsList = state => state.cate.goodsList
